package net.pws.oos.biz.query.impl;

import java.util.ArrayList;
import java.util.List;

import net.pws.common.persistence.IPage;
import net.pws.common.persistence.QueryRepository;
import net.pws.oos.biz.model.TaskTemplate;
import net.pws.oos.biz.query.TaskTemplateFinder;
import net.pws.oos.biz.query.parameter.TaskTemplateQueryParameter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("unchecked")
public class DefaultTaskTemplateFinder extends AbstractFinder implements
		TaskTemplateFinder {

	@Override
	public TaskTemplate getTemplate(String id) {
		return entityManager.find(TaskTemplate.class, id);
	}

	@Override
	public List<TaskTemplate> findChildren(String parentId) {
		String hql = QueryRepository.getInstance().get(
				"hql.findTemplateChildren");
		return entityManager.findList(hql, new Object[] { parentId });
	}

	@Override
	public int countTop(TaskTemplateQueryParameter parameter) {
		List<Object> params = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder();
		hql.append(QueryRepository.getInstance().get("hql.countTemplate"));
		buildQuery(hql, params, parameter);
		Number count = (Number) entityManager.findFirst(hql.toString(), params.toArray());
		return count.intValue();
	}

	@Override
	public List<TaskTemplate> listTop(TaskTemplateQueryParameter parameter) {
		List<Object> params = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder();
		hql.append(QueryRepository.getInstance().get("hql.listTemplate"));
		buildQuery(hql, params, parameter);
		IPage<TaskTemplate> page = entityManager.findPage(hql.toString(),
				params.toArray(), parameter.getStart(), parameter.getLimit());
		return page.getData();
	}

	private void buildQuery(StringBuilder hql, List<Object> params,
			TaskTemplateQueryParameter parameter) {
		if(hql == null || params == null || parameter == null) {
			return;
		}
		if (StringUtils.isNotBlank(parameter.getName())) {
			hql.append(" and t.name like ? ");
			params.add("%" + parameter.getName() + "%");
		}
		if (parameter.getEnable() != null) {
			hql.append("and t.enable = ?");
			params.add(parameter.getEnable());
		}
	}

}
